package com.jjb.www.ui.activity;

import android.util.Log;
import android.view.View;

import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.Permission;
import com.jjb.www.R;
import com.jjb.www.aop.Permissions;
import com.jjb.www.app.AppActivity;
import com.jjb.www.http.api.ConfirmQRLoginApi;
import com.jjb.www.http.model.HttpData;
import com.jjb.www.other.AppConfig;
import com.jjb.www.ui.dialog.CommonUseDialog;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import cn.bingoogolapple.qrcode.zxing.ZXingView;
/**
 *    author : Android CRG
 *    github : https://github.com/getActivity/AndroidProject
 *    time   : 2018/10/18
 *    desc   : 二维码扫码
 */
public class ScanQrCodeActivity extends AppActivity  implements QRCodeView.Delegate {
    private ZXingView mZXingView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_scan_qr_code;
    }

    @Override
    protected void initView() {
        mZXingView = findViewById(R.id.zxing_view);
        mZXingView.setDelegate(this);
    }

    @Permissions(Permission.CAMERA)
    @Override
    protected void initData() {

    }
    @Override
    public void onRightClick(View view) {
        ImageSelectActivity.start(this, data -> {
//            cropImageFile(new File(data.get(0)));
            Log.e("result==1==",data.get(0));
            String result = QRCodeDecoder.syncDecodeQRCode(data.get(0));
            Log.e("result==2==",result+"-------");
        });

    }
    @Override
    protected void onStop() {
        // 关闭摄像头预览，并且隐藏扫描框
        mZXingView.stopCamera();
        super.onStop();
    }

    @Override
    protected void onResume() {
        // 打开后置摄像头开始预览，但是并未开始识别
        mZXingView.startCamera();
        // 显示扫描框，并开始识别
        mZXingView.startSpotAndShowRect();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 销毁二维码扫描控件
        mZXingView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        // 停止识别
        mZXingView.stopSpot();
        if (result.startsWith("http")) {
            BrowserActivity.start(this, result);
        } else if (result.startsWith("jjb_web_exam")) {
            String str1 = result.substring(0, result.indexOf("|"));
            String str2 = result.substring(str1.length() + 2);
            String[] str3 = str2.split(",");
            int userId = Integer.parseInt(str3[0]);
            int studyWayId = Integer.parseInt(str3[1]);
            int postId = Integer.parseInt(str3[2]);
//            L.e("----userId-->>>", userId+"");
//            L.e("----studyWayId-->>>", studyWayId+"");
//            L.e("----postId-->>>", postId+"");
            if (userId != AppConfig.getInstance().getUserBean().getUser().getId()) {
                toast("登录账号不一致，请确认登录账号一致后重新扫码");
                finish();
            } else {

//                Intent intent = new Intent(this, SequentialPracticeActivity.class);
//                intent.putExtra("flag", 5);
//                intent.putExtra("study_way_id", studyWayId);
//                startActivity(intent);
            }
        } else {
            int index = result.indexOf("|");
            index = result.indexOf("|", index + 1);
            String qrId = result.substring(index + 1);
            //输出结果
            new CommonUseDialog.Builder(getContext())
                    .setHint("是否授权网页登录？")
                    .setListener(new CommonUseDialog.OnListener() {
                        @Override
                        public void onCompleted(BaseDialog dialog) {
                            qrCodeLogin(qrId);
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {

                        }
                    }).show();
        }
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = mZXingView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                mZXingView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                mZXingView.getScanBoxView().setTipText(tipText);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
//        L.e("打开相机出错");
    }

    private void qrCodeLogin(String qrId) {
        EasyHttp.post(this)
                .api(new ConfirmQRLoginApi()
                        .setQrId(qrId)
                )
                .request(new HttpCallback<HttpData<ConfirmQRLoginApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<ConfirmQRLoginApi.Bean> result) {
                        if (result.getData().getStatus() == 1) {
                            toast("登录成功");
                            finish();
                        }
                    }
                });
    }
}